<template>
  <div class="container">
    <div class="header">
      <div class="title">东软空气质量环保公众监控平台</div>
      <div class="datetime">{{ currentDateTime }}</div>
    </div>
    <div class="content">
      <div class="left-section">
        <div class="gauge-section">
          <div id="gauge1Chart" class="gauge-container"></div>
          <div id="gauge2Chart" class="gauge-container"></div>
        </div>
        <div id="distributionChart" class="chart-container"></div>
        <div id="trendChart" class="chart-container"></div>
      </div>
      <div id="chinaChart" class="china-chart"></div>
      <div class="right-section">
        <div id="pm25Chart" class="chart-container"></div>
        <div id="so2Chart" class="chart-container"></div>
        <div id="coChart" class="chart-container"></div>
      </div>
    </div>
    <div class="footer">
      <div class="footer-item">空气质量监测点数量: {{ airQualityPointCount }}</div>
      <div class="footer-item">空气质量良好天数: {{ goodAirDays }}</div>
      <div class="footer-item">空气质量污染天数: {{ pollutedAirDays }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import $axios from '../utils/axios'
import * as echarts from 'echarts'
import ChinaMap from '@/assets/chinaChange.json'

const airQualityPointCount = ref(0)
const goodAirDays = ref(0)
const pollutedAirDays = ref(0)

const fetchFooterData = async () => {
  const path = '/api/feedback/getCountData'
  const { data } = await $axios.get(path)
  console.log(data)
  if (data.code === '200') {
    airQualityPointCount.value = data.data.airQualityPointCount
    goodAirDays.value = data.data.goodAirDays
    pollutedAirDays.value = data.data.pollutedAirDays
  }
}
fetchFooterData()

// 时间显示
const currentDateTime = ref('')
const updateTime = () => {
  const now = new Date()
  const formattedTime = now.toLocaleString('zh-CN', { hour12: false })
  currentDateTime.value = formattedTime
}
setInterval(updateTime, 1000)

// ChinaCharts 数据初始化
const chinaData = ref([])
let chinaChartInstance = null
const initChinaData = async () => {
  const path = '/api/report/fullChinaCharts'
  const { data: res } = await $axios.get(path)
  if (res.code === '200') {
    chinaData.value = transformData(res.data)
    console.log('initChinaChart')
    initChinaChart()
  }
}

const transformData = (data) => {
  return data.map((item) => {
    const provinceName = Object.keys(item)[0]
    const aqilevel = item[provinceName]
    return { name: provinceName, value: aqilevel }
  })
}

const initChinaChart = () => {
  const chartElement = document.getElementById('chinaChart')
  if (echarts.getInstanceByDom(chartElement)) {
    echarts.dispose(echarts.getInstanceByDom(chartElement))
  }
  chinaChartInstance = echarts.init(chartElement)
  echarts.registerMap('china', ChinaMap)

  const option = {
    tooltip: {
      formatter: '{b}：{c}'
    },
    visualMap: {
      min: 1,
      max: 15,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      inRange: {
        color: ['#67C23A', '#FFFF00', '#FFA500', '#FF0000', '#800080']
      },
      calculable: true,
      textStyle: { color: '#ffffff' }
    },
    series: [
      {
        name: 'AQI',
        type: 'map',
        map: 'china',
        selectedMode: 'multiple',
        roam: false,
        label: {
          show: true,
          color: '#000',
          fontSize: 10,
          emphasis: {
            show: true,
            fontSize: 14
          }
        },
        itemStyle: {
          emphasis: {
            areaColor: 'rgba(128, 128, 128, 0.5)'
          }
        },
        data: chinaData.value
      }
    ]
  }
  chinaChartInstance.setOption(option)
}

// DistributionCharts 数据初始化
const distributionData = ref([])
let distributionChartInstance = null
const initDistributionData = async () => {
  const path = '/api/report/aqiDistribution'
  const response = await $axios.post(path)
  if (response.data.code === '200') {
    distributionData.value = response.data.data
    drawDistributionChart(response.data.data)
  }
}

const drawDistributionChart = (chartData) => {
  const chartElement = document.getElementById('distributionChart')
  if (echarts.getInstanceByDom(chartElement)) {
    echarts.dispose(echarts.getInstanceByDom(chartElement))
  }
  distributionChartInstance = echarts.init(chartElement)

  const colorMap = {
    优: '#67C23A',
    良: '#FFFF00',
    轻度污染: '#FFA500',
    中度污染: '#FF0000',
    重度污染: '#800080',
    严重污染: '#800000'
  }
  const option = {
    title: {
      text: 'AQI指数分布统计',
      left: 'center',
      textStyle: { color: '#ffffff' }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: '10%',
      data: chartData.map((item) => item.rankCategory),
      textStyle: { color: '#ffffff' }
    },
    series: [
      {
        name: 'AQI指数等级',
        type: 'pie',
        radius: '50%',
        center: ['50%', '40%'],
        data: chartData.map((item) => ({
          name: item.rankCategory,
          value: item.aqiNumber
        })),
        itemStyle: {
          color: function (params) {
            return colorMap[params.name] || '#000000'
          }
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  distributionChartInstance.setOption(option)
}

// TrendCharts 数据初始化
const trendData = ref([])
let trendChartInstance = null
const initTrendData = async () => {
  const path = '/api/report/aqiTrend'
  const { data: res } = await $axios.post(path)
  if (res.code === '200') {
    trendData.value = res.data
    trendData.value.forEach((item, index) => {
      item.id = index + 1
    })
    drawTrendChart()
  }
}

const drawTrendChart = () => {
  const chartElement = document.getElementById('trendChart')
  if (echarts.getInstanceByDom(chartElement)) {
    echarts.dispose(echarts.getInstanceByDom(chartElement))
  }
  trendChartInstance = echarts.init(chartElement)

  const option = {
    title: {
      text: '12个月内空气质量超标趋势',
      left: 'center',
      textStyle: { color: '#ffffff' }
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      orient: 'vertical',
      right: '10%',
      top: '5%',
      data: ['AQI空气质量指数超标数量'],
      textStyle: { color: '#ffffff' }
    },
    xAxis: {
      type: 'category',
      data: trendData.value.map((item) => item.yearMonth),
      axisLine: { lineStyle: { color: '#ffffff' } }
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#ffffff' } }
    },
    series: [
      {
        name: 'AQI空气质量指数超标数量',
        type: 'line',
        data: trendData.value.map((item) => item.aqiNumber),
        smooth: true
      }
    ]
  }
  trendChartInstance.setOption(option)
}

// ProGroupCharts 数据初始化
const proGroupData = ref([])
let pm25ChartInstance = null
let so2ChartInstance = null
let coChartInstance = null
const initProGroupData = async () => {
  const path = '/api/report/provinceAqi'
  const response = await $axios.post(path)
  if (response.data.code === '200') {
    proGroupData.value = response.data.data
    drawProGroupCharts()
  }
}

const drawProGroupCharts = () => {
  drawBarChart('pm25Chart', 'PM2.5浓度超标累计', proGroupData.value, 'pm25Statistics', pm25ChartInstance, '#4E9EFD')
  drawBarChart('so2Chart', 'SO2浓度超标累计', proGroupData.value, 'so2Statistics', so2ChartInstance, '#69C241')
  drawBarChart('coChart', 'CO浓度超标累计', proGroupData.value, 'coStatistics', coChartInstance, '#F26C6D')
}

const drawBarChart = (elementId, title, data, key, chartInstance, color) => {
  const chartElement = document.getElementById(elementId)
  if (echarts.getInstanceByDom(chartElement)) {
    echarts.dispose(echarts.getInstanceByDom(chartElement))
  }
  chartInstance = echarts.init(chartElement)

  const option = {
    title: {
      text: title,
      left: 'center',
      textStyle: { color: '#ffffff' }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    xAxis: {
      type: 'category',
      data: data.map((item) => item.provinceName),
      axisLine: { lineStyle: { color: '#ffffff' } },
      axisLabel: {
        rotate: 45, // 旋转角度
        fontSize: 10, // 字体大小
        interval: 0 // 强制所有标签显示
      }
    },
    yAxis: {
      type: 'value',
      axisLine: { lineStyle: { color: '#ffffff' } }
    },
    series: [
      {
        name: title,
        type: 'bar',
        data: data.map((item) => item[key]),
        itemStyle: { color: color }
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        show: true,
        xAxisIndex: [0],
        start: 0,
        end: 100
      }
    ]
  }
  chartInstance.setOption(option)
}

// GaugeCharts 数据初始化
let gauge1ChartInstance = null
let gauge2ChartInstance = null
const drawGaugeChart = (elementId, title, value, chartInstance) => {
  const chartElement = document.getElementById(elementId)
  if (echarts.getInstanceByDom(chartElement)) {
    echarts.dispose(echarts.getInstanceByDom(chartElement))
  }
  chartInstance = echarts.init(chartElement)

  const option = {
    title: {
      text: title,
      left: 'center',
      textStyle: { color: '#ffffff', fontSize: 14 }
    },
    series: [
      {
        type: 'gauge',
        radius: '100%', // 调整表盘的半径
        detail: { formatter: '{value}%', color: '#ffffff', fontSize: 20 },
        data: [{ value: value, name: '' }],
        axisLabel: {
          distance: 5,
          color: '#ffffff',
          fontSize: 10
        },
        pointer: {
          width: 2
        },
        splitLine: {
          length: 10,
          lineStyle: {
            color: '#ffffff'
          }
        },
        title: {
          offsetCenter: [0, '70%'],
          color: '#ffffff',
          fontSize: 12
        },
        axisLine: {
          lineStyle: {
            width: 8,
            color: [
              [0.3, '#67C23A'],
              [0.7, '#E6A23C'],
              [1, '#F56C6C']
            ]
          }
        }
      }
    ]
  }
  chartInstance.setOption(option)
}

const provinceCover = ref(0)
const cityCover = ref(0)

const fetchGaugeData = async () => {
  const path = '/api/feedback/getCoverData'
  const { data } = await $axios.get(path)
  if (data.code === '200') {
    provinceCover.value = data.data.provinceCover
    cityCover.value = data.data.cityCover

    // 绘制仪表盘图表
    drawGaugeChart('gauge1Chart', '省网格覆盖率', provinceCover.value, gauge1ChartInstance)
    drawGaugeChart('gauge2Chart', '市网格覆盖率', cityCover.value, gauge2ChartInstance)
  }
}
fetchGaugeData()

// 路由变化监听
const route = useRoute()
watch(route, () => {
  onRouteChange()
})

// 页面挂载和路由变化时初始化图表和数据
const onRouteChange = () => {
  initChinaData()
  initDistributionData()
  initTrendData()
  initProGroupData()
}

onMounted(() => {
  onRouteChange()
})
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100%;
  background-color: #1f2d3d;
  color: #ffffff;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #293b5a;
}

.title {
  font-size: 24px;
}

.datetime {
  font-size: 14px;
}

.content {
  display: flex;
  flex: 1;
  padding: 10px;
}

.left-section,
.right-section {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  width: 20%;
}

.gauge-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.china-chart {
  flex: 1;
  width: 60%;
  margin: 0 10px;
}

.chart-container {
  width: 100%;
  height: 200px;
  margin-top: 20px;
}

.gauge-container {
  width: 120%;
  height: 220px;
}

.footer {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px;
  background-color: #293b5a;
}

.footer-item {
  font-size: 16px;
}
</style>
